<?php
namespace app\api\controller;

use think\Controller;
use think\Db;
use app\common\model\TmoneyLogs as TmoneyLogsModel;

class Payment extends Controller
{
    protected $tmoney_logs_model;
    /**
     * 析构流函数
     */
    public function __construct(){
        parent::__construct();
        // tpshop 订单支付提交
        $pay_radio = "pay_code=weixinsmall";
        if(!empty($pay_radio)) 
        {                         
            $pay_radio = parse_url_param($pay_radio);
            $this->pay_code = $pay_radio['pay_code']; // 支付 code
        }
        if(empty($this->pay_code))
            exit('pay_code 不能为空');
        // 导入具体的支付类文件                
        include_once  "../plugins/payment/{$this->pay_code}/{$this->pay_code}.class.php"; // D:\wamp\www\svn_tpshop\www\plugins\payment\alipay\alipayPayment.class.php   
        $code = '\\'.$this->pay_code; // \alipay
        $this->payment = new $code();
    }

    public function getCode(){
        $data = $this->request->param();
        $openid = $data['openid'];
        if(!$openid){
            $user_id = $data['user_id'];
            if(!$user_id){
                return json(['msg'=>'缺少参数user_id']);
            }else{
                $openid = Db::name('hird_user')->field('openid')->where('user_id',$user_id)->find();
                return $openid;
            }
        }

        //生成订单
        $order_data = [
            'order_sn'=>date('YmdHis').rand(1000,9999),
            'u_id'=>$data['user_id'],
            'openid'=>$data['openid'],
            'money'=>$data['money'],
            'create_time'=>date('Y-m-d H:i:s'),
        ];
        $order_id = Db::name('order')->insertGetId($order_data);
        if(!$order_id){
            return json(['msg'=>'缺少参数order_id']);
        }
        // 修改订单的支付方式
        $payment_arr = Db::name('Plugin')->where("`type` = 'payment'")->column("code,name");
        Db::name('order')->where("order_id",$order_id)->update(array('pay_code'=>$this->pay_code,'pay_name'=>$payment_arr[$this->pay_code]));
        // var_dump($payment_arr);exit();
        
        $order = Db::name('order')->where("order_id", $order_id)->find();
        if($order['status'] == 1){
            $this->error('此订单，已完成支付!');
        }            
        // tpshop 订单支付提交
        $pay_radio = $data['pay_radio'];
        $config_value = parse_url_param($pay_radio); // 类似于 pay_code=alipay&bank_code=CCB-DEBIT 参数

        // var_dump($config_value);exit();
        // var_dump($this->pay_code.','.$openid);exit();
        //微信JS支付
       if($this->pay_code == 'weixinsmall' && $openid ){
           $code_str = $this->payment->get_xpay($order,$openid,$config_value);
           $miniProgramInfo = Db::name('plugin')->field('config_value')->where('code',$this->pay_code)->find();
           $miniProgramInfo = unserialize($miniProgramInfo['config_value']);
           $timestamp = (string)time();
        //    return "appId=".$miniProgramInfo['appid']."&nonceStr=".$code_str['nonce_str']."&package=prepay_id=".$code_str['prepay_id']."&signType=MD5&timeStamp=".(string)time()."&key=".$miniProgramInfo['key'];
           $code_str['paySign'] = strtoupper(md5("appId=".$miniProgramInfo['appid']."&nonceStr=".$code_str['nonce_str']."&package=prepay_id=".$code_str['prepay_id']."&signType=MD5&timeStamp=".$timestamp."&key=".$miniProgramInfo['key']));
        //    return json($code_str);
       }else{
        
           // $code_str = $this->payment->get_xpay($order,$config_value);
        //    echo "<pre>";
        //    var_dump($code_str);exit();
        //    echo "</pre>";
       }

        $arr = [
            'timeStamp'=> $timestamp,
            'nonceStr'=> $code_str['nonce_str'],
            'package'=> $code_str['prepay_id'],
            'signType'=> 'MD5',
            'paySign'=> $code_str['paySign'],
        ];

        return json($arr);
    }

    // 服务器点对点 // http://www.tp-shop.cn/index.php/Home/Payment/notifyUrl        
    public function notifyUrl(){            
        $this->payment->response();
        exit();
    }

    //企业付款到零钱
    public function sendSmallChange(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $openid = $data['openid'];
            //生成订单
            $order_data = [
                'order_sn'=>date('YmdHis').rand(1000,9999),
                'u_id'=>$data['user_id'],
                'openid'=>$openid,
                'money'=>$data['money'],
                'create_time'=>date('Y-m-d H:i:s'),
                'pay_code'=>$this->pay_code,
                'pay_name'=>'企业支付到零钱',
            ];
            $order_id = Db::name('order')->insertGetId($order_data);
            $order = Db::name('order')->where("order_id", $order_id)->find();
            $rmd = Db::name('third_user')->where('openid',$openid)->value('remainder');
            if($rmd < $data['money']){
                return json(['status'=>0,'msg'=>'提现余额不足']);
            }else{
                if($this->pay_code == 'weixinsmall' && $openid ){
                    $code_str = $this->payment->qy_send_schenge($order,$openid);
                    if($code_str['result_code'] == 'SUCCESS'){
                        $update_data = ['remainder'=>$rmd - $data['money']];
                        Db::name('third_user')->where('openid',$openid)->update($update_data);
                    }
                    $code_str['openid'] = $openid;
                    $code_str['take_money'] = $data['money'];
                    $this->tmoney_logs_model = new TmoneyLogsModel();
                    $this->tmoney_logs_model->allowField(true)->save($code_str);
                    return json($code_str);
                }
            }
        }
    }
}